<?php

namespace app\service\controller;

use think\Session;
use app\index\model\User;
use app\admin\model\Service;
use app\service\model\Chatlog;
use app\wechat\model\OauthUser;
use app\service\model\ServiceLog;

class Index extends Base
{
    public function index()
    {
        if (isMobile()) {
            return $this->redirect('service/index/mobile');
        }
        // 客服信息
        $userInfo = db('services')->where('id', cookie('l_user_id'))->find();

        $this->assign([
            'uinfo' => $userInfo,
            'word' => db('words')->select(),
            'groups' => Service::ROLES_MAP,
            'status' => db('config')->where('id', 1)->find()
        ]);

        return $this->fetch();
    }

    // 获取服务用户列表
    public function getUserList()
    {
        if (request()->isAjax()) {
            $query = User::with(['shop', 'service', 'department', 'market']);
            if (!cookie('l_user_admin')) {
                $sevice = Service::find(cookie('l_user_id'));
                switch ($sevice->role) {
                    case Service::ROLE_SERVICE:
                        $query->where('service_id', $sevice->id);
                        break;
                    case Service::ROLE_MARKET:
                        $query->where('market_id', $sevice->id);
                        break;
                    case Service::ROLE_SHOP:
                        $query->where('shop_id', $sevice->id);
                        break;
                    case Service::ROLE_DEPARTMENT:
                        $query->where('department_id', $sevice->id);
                        break;
                    default:
                        return json(['code' => 1, 'data' => [], 'msg' => 'ok']);
                }
                $query->field('ws_users.*')->join('ws_chat_log', 'ws_chat_log.user_id = ws_users.id', 'left')->order('ws_chat_log.created_at', 'desc');
            } else {
                $query->field('ws_users.*')->join('ws_chat_log', 'ws_chat_log.user_id = ws_users.id', 'inner')->order('ws_chat_log.created_at', 'desc');
            }
            $userList = $query->select()->map(function ($user) {
                $user->shop ??= [];
                $user->service ??= [];
                $user->department ??= [];
                $user->market ??= [];
                $user->avatar = $user->headimgurl;
                $user->name = $user->name;
                return $user->toArray();
            });
            return json(['code' => 1, 'data' => $userList, 'msg' => 'ok']);
        }
    }

    // 获取聊天记录
    public function getChatLog()
    {
        if (request()->isAjax()) {
            $param = input('param.');

            $limit = 10; // 一次显示10 条聊天记录
            $offset = ($param['page'] - 1) * $limit;

            $logs = db('chat_log')->where('user_id', $param['uid'])->limit($offset, $limit)->order('id', 'desc')->select();
            $total =  db('chat_log')->where('user_id', $param['uid'])->count();

            foreach ($logs as $key => $vo) {
                $logs[$key]['type'] = 'user';
                $logs[$key]['time_line'] = date('Y-m-d H:i:s', $vo['time_line']);

                if ($vo['from_id'] == 'KF' . cookie('l_user_id')) {
                    $logs[$key]['type'] = 'mine';
                }
            }

            return json(['code' => 1, 'data' => $logs, 'msg' => intval($param['page']), 'total' => ceil($total / $limit)]);
        }
    }

    // ip 定位
    public function getCity()
    {
        $ip = input('param.ip');

        $ip2region = new \Ip2Region();
        $info = $ip2region->btreeSearch($ip);
        $city = explode('|', $info['region']);

        if (0 != $info['city_id']) {
            return json(['code' => 1, 'data' => $city['2'] . $city['3'] . $city['4'], 'msg' => 'ok']);
        } else {
            return json(['code' => 1, 'data' => $city['0'], 'msg' => 'ok']);
        }
    }

    public function mobile()
    {
        if (!isMobile()) {
            return $this->redirect('service/index/index');
        }
        $wechat_user = Session::get('wechat_user');
        // $wechat_user = OauthUser::find(9);
        if (!$wechat_user) {
            // $wechat_user = \app\wechat\model\OauthUser::find(request()->get('id', 1));
            Session::set('target_url', url('/service/index/mobile', null, null, true));
            return $this->redirect('wechat/user/login');
        }
        // 客服信息
        $userInfo = Service::where('openid', $wechat_user['openid'])->find();
        if (!$userInfo) {
            return $this->redirect('/');
        }
        $userInfo['title'] = $userInfo->user_name;
        if ($userInfo->service_name) {
            $userInfo['title'] = trim($userInfo->service_name . '-' . $userInfo['title'], '-');
        }
        $this->assign([
            'uinfo' => $userInfo,
            'word' => db('words')->select(),
            'groups' => Service::ROLES_MAP,
            'status' => db('config')->where('id', 1)->find(),
            'init' => json_encode([])
        ]);

        return $this->fetch();
    }

    public function init()
    {
        $wechat_user = Session::get('wechat_user');

        /**
         * @var Service
         */
        $userInfo = Service::where('openid', $wechat_user['openid'])->find();
        $mine = [
            'username' => $userInfo->user_name,
            'id' => 'KF' . $userInfo->id,
            'status' => 'online',
            'sign' => '签名',
            'avatar' => $userInfo->user_avatar
        ];

        $forget_key = '';
        switch ($userInfo->role) {
            case Service::ROLE_DEPARTMENT:
                $forget_key = 'department_id';
                break;
            case Service::ROLE_SHOP:
                $forget_key = 'shop_id';
                break;
            case Service::ROLE_MARKET:
                $forget_key = 'market_id';
                break;
            case Service::ROLE_SERVICE:
                $forget_key = 'service_id';
                break;
            default:
                break;
        }

        $group = User::where($forget_key, $userInfo->id)->select()->map(fn (User $user) => [
            'groupname' => $user->name ?: $user->nickname,
            'id' => $user->id,
            'avatar' => $user->headimgurl
        ]);
        return [
            'mine' => $mine,
            'group' => $group
        ];
    }

    public function userInfo()
    {
        if (request()->isAjax()) {
            $id = input('id');
            /**
             * @var User
             */
            $userInfo = User::where('id', $id)->with(['shop', 'market', 'department', 'service'])->find();
            $userInfo['service_list'] = array_filter([['user_name' => $userInfo->name, 'user_avatar' => $userInfo->headimgurl], $userInfo->shop, $userInfo->market, $userInfo->department, $userInfo->service]);
            return $userInfo;
        }
    }

    public function getUserChatLog($id)
    {
        $wechat_user = Session::get('wechat_user');
        $userInfo = Service::where('openid', $wechat_user['openid'])->find();
        $query = Chatlog::field([
            "from_avatar" => "avatar",
            "content",
            "user_id" => "id",
            "from_id",
            "time_line" => "timestamp",
            "'group' as type",
            "from_name" => "username",
            "id" => "chat_id"
        ])->where('user_id', $id)->order('chat_id', 'desc')->limit(10);

        if ($chat_id = $this->request->get('chat_id')) {
            $query->where('id', '<', $chat_id);
        }
        $logs = $query->select()->reverse();
        $paylod = collect();
        $time = null;

        foreach ($logs as $log) {
            $time_line = date('YmdHi', $log->timestamp);
            if ($time_line != $time) {
                $time = $time_line;
                $paylod->push([
                    'time' => date('Y-m-d H:i:s', $log->timestamp),
                    'type' => 'time',
                ]);
            }
            $log->type = 'message';
            $log->mine = $log->from_id == "KF" . $userInfo['id'];
            $paylod->push($log->toArray());
        }
        return $paylod->reverse()->values();
    }

    public function syncChatList()
    {
        $wechat_user = Session::get('wechat_user');

        /**
         * @var Service
         */
        $userInfo = Service::where('openid', $wechat_user['openid'])->find();
        $forget_key = '';
        switch ($userInfo->role) {
            case Service::ROLE_DEPARTMENT:
                $forget_key = 'department_id';
                break;
            case Service::ROLE_SHOP:
                $forget_key = 'shop_id';
                break;
            case Service::ROLE_MARKET:
                $forget_key = 'market_id';
                break;
            case Service::ROLE_SERVICE:
                $forget_key = 'service_id';
                break;
            default:
                break;
        }

        return User::where($forget_key, $userInfo->id)->select()->map(function ($user) {
            $log = Chatlog::where('user_id', $user->id)->order('id', 'desc')->find();
            if (!$log) return null;
            return [
                'type' => 'group',
                'groupname' => $user->name ?: $user->nickname,
                'name' => $log->from_name,
                'id' => $user->id,
                'avatar' => $user->headimgurl,
                'content' => $log->content,
                'time' => $log->time_line
            ];
        })->filter()->sortBy('time')->values();
    }
}
